package com.goktech.interceptor;

import cn.hutool.core.bean.BeanUtil;
import com.goktech.entityDto.UserDto;
import com.goktech.pojo.User;
import com.goktech.service.UserService;
import com.goktech.utils.ParseJwt;
import com.goktech.utils.UserHolder;
import io.jsonwebtoken.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.goktech.utils.Constants.*;

@Component
public class RefreshTokenInterceptor implements HandlerInterceptor {
    @Resource
    private UserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("RefreshTokenInterceptor");
        // 获取请求头中的 token
        String authorization = request.getHeader("Authorization");
        // 判断 token 是否为空
        if (ObjectUtils.isEmpty(authorization)) return true;
        // token 不为空, 获取真实的 token
        String token = authorization.substring(7);
        // 效验 token 合法性
        Claims claims = null;
        try {
            // 解析 token
            claims = ParseJwt.parseToken(token);
            // 获取用户ID
            Long id = Long.valueOf(claims.getId());
            // 查询是否存在此用户
            User user = userService.getById(id);
            if (ObjectUtils.isEmpty(user)) {
                // 不存在, 拦截, 返回 401
                System.out.println("不存在此用户");
                response.setStatus(401);
                return false;
            }
            // 基于 token 获取 redis 中的用户
            Map<Object, Object> map = stringRedisTemplate.opsForHash().entries(LOGIN_USER_KEY + token);
            if (map.isEmpty()) {
                // 不存在, 拦截, 返回 401
                System.out.println("redis 中不存在用户");
                response.setStatus(401);
                return false;
            }
            // 填充 UserDTO 通过 map
            UserDto userDto = BeanUtil.fillBeanWithMap(map, new UserDto(), false);
            // 保存用户信息到 ThreadLocal
            UserHolder.saveUser(userDto);
            // 刷新 token 有效期
            stringRedisTemplate.expire(LOGIN_USER_KEY + token, LOGIN_USER_TTL, TimeUnit.SECONDS);
            // 放行
            return true;
        } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | SignatureException | IllegalArgumentException e) {
            System.out.println("效验失败");
            System.out.println(e);
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 移除用户
        UserHolder.removeUser();
    }
}
